<!-- 合同列表-采购类合同- -->
<template>
  <div class="contract-list">
    <a-space class="contract-list-header" :size="30">
      <div style="padding: 15px">
        <a-space>
          <a-input
            :style="{ width: '380px' }"
            placeholder="请输入采购类合同搜索内容"
            v-model="contractSelectSearch"
            @change="search"
          >
            <template #prefix>
              <a-select
                :style="{ width: '120px' }"
                placeholder="请选择"
                v-model="contractSelectVal"
              >
                <a-option value="con_name">合同名称</a-option>
                <a-option value="con_num">合同编号</a-option>
                <a-option value="ccli_name">客户名称</a-option>
                <a-option value="our_ord_man">我方签约人</a-option>
              </a-select>
            </template>
          </a-input>

          <a-input-group>
            <a-select
              :style="{ width: '120px' }"
              placeholder="请选择"
              v-model="contractSelectVal"
            >
              <a-option value="name">合同名称</a-option>
              <a-option value="number">合同编号</a-option>
              <a-option value="clientName">客户名称</a-option>
              <a-option value="ourSignUser">我方签约人</a-option>
            </a-select>
            <a-input-search
              search-button
              placeholder="请输入销售类合同搜索内容"
              v-model="contractSelectSearch"
              @change="search"
            />
          </a-input-group>
          <a-popover position="right">
            <icon-exclamation-circle
              :style="{
                position: 'relative',
                marginLeft: '10px',
                color: 'red',
              }"
              :size="16"
            />
            <template #content>
              <p> 可以输入合同名称、合同编号、客户名称和我方签约人进行搜索 </p>
            </template>
          </a-popover>
          <a-select placeholder="请选择" v-model="ctype" @change="search">
            <template #prefix>类型：</template>
            <a-option
              v-for="item in ContractType"
              :key="item.id"
              :value="item.id"
              >{{ item.name }}</a-option
            >
          </a-select>
        </a-space>
      </div>

      <div>
        <a-space>
          <a-button type="outline" @click="reset">
            <template #icon>
              <icon-refresh />
            </template>
            <template #default>重置</template>
          </a-button>

          <a-button status="success">
            <template #icon>
              <icon-download />
            </template>
            <template #default>导入</template>
          </a-button>

          <a-button status="warning">
            <template #icon>
              <icon-export rotate="-90" />
            </template>
            <template #default>导出</template>
          </a-button>

          <!-- <a-button>批量操作</a-button> -->
          <a-button type="primary" @click="showFormHeaderSetting"
            >表头设置</a-button
          >
        </a-space>
      </div>
    </a-space>
    <div style="padding-left: 15px">
      <tableTurn
        :tableData="getContractListData"
        :args="args"
        ref="tableTurnRef"
      >
        <a-table-column :width="80" align="center">
          <template #title> 序号 </template>
          <template #cell="{ rowIndex }">
            {{ rowIndex + 1 }}
          </template>
        </a-table-column>
        <a-table-column
          :title="item.name"
          v-for="(item, index) in selectedHeader"
          :key="index"
          :data-index="item.code"
          align="center"
          :width="200"
        >
          <!-- 审批状态 -->
          <template v-if="item.code === 'state'" #cell="{ record }">
            <div class="use-state">
              <div
                class="cycle"
                :class="
                  record.state === 1
                    ? 'greyColor-cycle'
                    : record.state === 2
                    ? 'greyColor-cycle'
                    : record.state === 3
                    ? 'blueColor-cycle'
                    : record.state === 4
                    ? 'greenColor-cycle'
                    : record.state === 5
                    ? 'redColor-cycle'
                    : record.state === 6
                    ? 'blueColor-cycle'
                    : 'greyColor-cycle'
                "
              >
              </div>
              <div
                :class="
                  record.state === 1
                    ? 'greyColor'
                    : record.state === 2
                    ? 'greyColor'
                    : record.state === 3
                    ? 'blueColor'
                    : record.state === 4
                    ? 'greenColor'
                    : record.state === 5
                    ? 'redColor'
                    : 'greenColor'
                "
                >{{
                  record.state === 1
                    ? '待提交'
                    : record.state === 2
                    ? '待审核'
                    : record.state === 3
                    ? '审核中'
                    : record.state === 5
                    ? '不通过'
                    : '通过'
                }}</div
              >
            </div>
          </template>
          <!-- 执行状态 -->
          <template
            v-else-if="item.code === 'executionState'"
            #cell="{ record }"
          >
            <div class="use-state">
              <div
                class="cycle"
                :class="
                  record.state === 6
                    ? 'greenColor-cycle'
                    : record.state === 4
                    ? 'blueColor-cycle'
                    : 'greyColor-cycle'
                "
              >
              </div>
              <div
                :class="
                  record.state === 6
                    ? 'greenColor'
                    : record.state === 4
                    ? 'blueColor'
                    : 'greyColor'
                "
                >{{
                  record.state === 4
                    ? '执行中'
                    : record.state === 5
                    ? '待执行'
                    : record.state === 6
                    ? '已完成'
                    : '待执行'
                }}</div
              >
            </div>
          </template>
          <!-- 合同类型 -->
          <template v-else-if="item.code === 'ctypeId'" #cell="{ record }">
            {{ record.typeName }}
          </template>
          <!-- 合同创建时间item -->
          <template v-else-if="item.code === 'createdAt'" #cell="{ record }">
            {{ dayjs(record.createdAt).format('YYYY-MM-DD hh:mm:ss') }}
          </template>
          <!-- 签约时期 -->
          <template v-else-if="item.code === 'orderTime'" #cell="{ record }">
            {{ dayjs(record.orderTime).format('YYYY-MM-DD hh:mm:ss') }}
          </template>
          <!-- 结束日期 -->
          <template v-else-if="item.code === 'endTime'" #cell="{ record }">
            {{ dayjs(record.endTime).format('YYYY-MM-DD hh:mm:ss') }}
          </template>
        </a-table-column>

        <!-- 操作item -->
        <a-table-column align="center" :width="300" fixed="right" title="操作">
          <template #cell="{ record, rowIndex }">
            <a-button
              v-if="record.state === 1 || record.state === 5"
              type="text"
              :style="{
                backgroundColor: '#31C27C',
                color: '#fff',
              }"
              @click="submit(record)"
              >{{ record.state === 1 ? '提交' : '重新提交' }}</a-button
            >
            <a-button
              type="text"
              v-if="record.state === 1 || record.state === 5"
              @click="editContract(record.id)"
              >进入详情</a-button
            >
            <a-button
              type="text"
              v-if="record.state === 2 || record.state === 3"
              @click="editContract(record.id)"
              >查看详情</a-button
            >
            <!-- <a-button
              type="text"
              v-if="record.state === 4"
              @click="CreateOrder(record.id)"
              >创建订单</a-button
            > -->
            <a-button
              type="text"
              v-if="record.state === 4"
              @click="goDetail(record.id)"
              >档案</a-button
            >
            <a-button type="text" v-if="record.state === 4">变更</a-button>
            <a-popconfirm
              @ok="changeState(record.id, record.useState)"
              content="确定修改状态吗？"
              type="error"
              v-if="record.state === 4"
            >
              <a-button
                :style="{
                  color: record.state === 5 ? 'red' : '',
                }"
                status="danger"
                type="text"
              >
                终止
              </a-button>
            </a-popconfirm>
            <a-popconfirm
              v-if="record.state === 1 || record.state === 5"
              @ok="deleteItem(record.id, rowIndex)"
              content="确定删除吗"
              type="error"
            >
              <a-button
                type="text"
                :style="{
                  color: 'red',
                }"
                >删除</a-button
              >
            </a-popconfirm>
          </template>
        </a-table-column>
      </tableTurn>
    </div>
    <FormHeaderSetting
      v-model:visible="formHeaderSettingVisible"
      title="合同列表表头设置"
      :resultList="headerSetting.list"
      @headerSave="headerSave"
      :forbidList="forbidList"
    ></FormHeaderSetting>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, ref, computed, onMounted } from 'vue';
  import { useRouter } from 'vue-router';
  import { pageData as IpageData } from '@/types/global';
  import {
    GetContractHeader,
    PutContractHeader,
    GetContractListAll,
    DeleteContract,
    PutContract,
  } from '@/api/contract-management/contract-list/index';
  import cloneDeep from 'lodash.clonedeep';
  import dayjs from 'dayjs';
  import { formHeaderSetting } from '@/types/global';
  import * as apiList from '@/api/contract-management/base-setting/type-contract/index';

  const router = useRouter();
  const headerSetting = reactive<formHeaderSetting>({
    list: [],
  });

  const forbidList = reactive(['salesName']); // 禁止移动的表头， (合同审核状态、操作)
  // 获取登录信息
  const loginInfo = JSON.parse(sessionStorage.getItem('loginInfo') as any);
  const ContractType = ref();
  const getType = async () => {
    const res = await apiList.GetContractTypeSetting();
    ContractType.value = res.contractType;
  };
  getType();
  // 表格配置
  const args = reactive({
    stripe: true,
    rowSelection: {
      type: 'checkbox',
      showCheckedAll: true,
      onlyCurrent: false,
    },
    scroll: {
      // y: 500,
    },
    bordered: {
      headerCell: true,
    },
    rowKey: 'name', // 批量选择按钮 以合同名称来作为key
  });
  let tableTurnRef: any = ref(); // 储存table的ref
  let isFirstSelect = ref(true);

  let contractSelectVal = ref('con_name'); // 当前下拉选择的值,默认值为合同编号
  let contractSelectSearch = ref(''); // 搜索框的值
  let contractNameSearch = ref('');

  // 获取合同列表数据
  // const getContractListData = async (pageData?: any) => {
  //   isFirstSelect.value = false;
  //   try {
  //     const res = await GetContractListAll({
  //       ...pageData,
  //       name: isFirstSelect.value ? undefined : contractNameSearch.value,
  //       [contractSelectVal.value]: isFirstSelect.value
  //         ? undefined
  //         : contractSelectSearch.value,
  //       ctype: 2,
  //     });
  //     isFirstSelect.value = false;
  //     return Promise.resolve(res);
  //   } catch (err: unknown) {
  //     console.log(err);
  //   }
  // };
  const getContractListData = async (pageData?: any) => {
    try {
      // const listData = {
      //   [contractSelectVal.value]: contractSelectSearch.value,
      // };
      const res = await GetContractListAll({
        parentType: 2,
        ...pageData,
        // ...listData,
      });
      return Promise.resolve(res);
    } catch (err: unknown) {
      console.log(err);
    }
  };

  // 搜索框
  const search = async () => {
    tableTurnRef.value.loadData();
  };

  // 获取表头设置列表
  const getHeaders = async () => {
    try {
      const tableHead = await GetContractHeader({
        type: 2,
        userId: loginInfo.userId,
      });
      headerSetting.list = tableHead.extends;
    } catch (error: unknown) {
      console.log(error);
    }
  };
  getHeaders();

  // 在表格上显示的表头
  // const selectedHeader = computed(() => {
  //   const arr: formHeaderSetting['list'] = [];
  //   headerSetting.list.forEach((item) => {
  //     if (item.isDefault === 1) {
  //       arr.push(item);
  //     }
  //   });
  //   return arr;
  // });
  const selectedHeader = computed(() => {
    return headerSetting.list.filter((item) => item.isDefault === 1);
  });

  let formHeaderSettingVisible = ref<boolean>(false); // 是否显示表头设置组件

  // 表头设置按钮
  const showFormHeaderSetting = () => {
    formHeaderSettingVisible.value = true;
  };

  // 表头设置保存后返回的自定义事件
  const headerSave = async (headerList: formHeaderSetting['list']) => {
    try {
      const data = {
        type: 2,
        userId: loginInfo.userId,
        extend: JSON.stringify(headerList),
      };
      await PutContractHeader(data);
      headerSetting.list = [...headerList];
    } catch (err) {
      console.log(err);
    }
  };

  // 去往对应的详情页面
  const editContract = (id: number) => {
    router.push({
      name: 'EditContract',
      query: { id },
    });
  };

  const CreateOrder = async (id: number) => {
    router.push({ name: 'SalesOrderAdd', query: { contractId: id } });
  };
  // 去往合同档案
  const goDetail = (id: number) => {
    router.push({
      name: 'ContractDetail',
      query: { id },
    });
  };

  // 删除一项
  const deleteItem = async (id: number, rowIndex: number) => {
    try {
      await DeleteContract({
        id,
      });
      tableTurnRef.value.loadData();
    } catch (err: unknown) {
      console.log(err);
    }
  };

  const submit = async (record) => {
    record.state = 3;
    await PutContract(record);
  };

  // 监听键盘回车，按了回车也会查询
  const keyDown = (e: any) => {
    if (e.keyCode === 13) {
      tableTurnRef.value.loadData();
    }
  };

  onMounted(() => {
    // 监听键盘事件
    window.addEventListener('keydown', keyDown);
  });
</script>

<style scoped lang="less">
  .contract-list {
    :deep(.arco-table-tr) {
      height: 50px;
    }
    :deep(.arco-space) {
      justify-content: space-between;
    }
    // :deep(.arco-space-horizontal .arco-space-item) {
    //   margin-left: 50px;
    // }
    &-header {
      display: flex;
      justify-content: space-between;
      // width: 100%;
      // margin-bottom: 10px;
      // margin-top: 5px;
      // :deep(.arco-btn-secondary) {
      //   color: #165dff;
      //   margin-right: 20px;
      // }
    }

    .use-state {
      display: flex;
      justify-content: center;
      text-align: center;
      .cycle {
        position: relative;
        width: 16px;
        height: 16px;
        border-radius: 50%;
        content: '';
        display: inline-block;
        top: 3px;
        right: 10px;
      }
    }

    // 待提交、待审核、已完成
    .greyColor {
      color: #c9cdd4;
    }
    .greyColor-cycle {
      background-color: #c9cdd4;
    }

    // 审核中、执行中
    .blueColor {
      color: #156dff;
    }
    .blueColor-cycle {
      background-color: #156dff;
    }

    // 已通过
    .greenColor {
      color: #31c273;
    }
    .greenColor-cycle {
      background-color: #31c273;
    }

    // 不通过
    .redColor {
      color: #f53f3f;
    }
    .redColor-cycle {
      background-color: #f53f3f;
    }
  }
</style>
